package cn.dakaqi.web.api.v1;

import cn.dakaqi.activity.recruit.services.ActivityRecruitService;
import cn.dakaqi.activity.services.ActivityService;
import cn.dakaqi.entities.*;
import cn.dakaqi.group.recruit.services.GroupRecruitService;
import cn.dakaqi.group.services.GroupService;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.sys.topic.services.IndexDataService;
import cn.dakaqi.sys.topic.services.SysTopicService;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import cn.dakaqi.web.util.common.DKQPage;
import cn.dakaqi.web.vo.SearchResultVO;
import com.alibaba.fastjson.JSON;
import com.wordnik.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.web.MediaTypes;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chunyang on 2016/4/21.
 */
@RestController
@RequestMapping(value = "/api/v1/index")
@Api(value = "首页数据API")
public class IndexRestController
{
    @Autowired
    ActivityService activityService;
    @Autowired
    GroupService groupService;
    @Autowired
    SysTopicService sysTopicService;
    @Autowired
    GroupRecruitService groupRecruitService;
    @Autowired
    ActivityRecruitService activityRecruitService;
    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    IndexDataService indexDataService;


    @RequestMapping(value = "/{city}/{memberCode}/{pageNumber}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> memberCode(@PathVariable("city") String city,@PathVariable("memberCode") String memberCode, @PathVariable("pageNumber") int pageNumber)
    {
        String key = "IndexRestController_memberCode_"+pageNumber + memberCode;
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> resultMap = new HashMap<String, Object>();

        try
        {
//        if(redisClientTemplate.exists(key))
//        {
//            jsonResult.setCode(JsonResult.CODE_SUCCESS);
//            jsonResult.setMessage("查询成功");
//            resultMap = (Map<String, Object>)JSON.parse(redisClientTemplate.get(key));
//            jsonResult.setData(resultMap);
//        }
//        else
            {
                if (null != memberCode && !"null".equals(memberCode.trim().toLowerCase()) && StringUtils.isNotBlank(memberCode))
                {
                    //根据条件，找出当前用户所喜好的标签
                    Volunteer volunteer = volunteerService.findByMemberCode(memberCode);
                    String cityStr;
                    if("default".equalsIgnoreCase(city)){
                        cityStr = volunteer.getCity();
                    }else{
                        cityStr = city;
                    }
                    if (null != volunteer)
                    {
                        Page<IndexData> dataPage = indexDataService.findAll(cityStr, volunteer.getJob(), volunteer.getServiceField(), volunteer.getSkill(), pageNumber);

                        resultMap.put("list", dataPage.getContent());
                        resultMap.put("page", new DKQPage(dataPage));
                        jsonResult.setCode(JsonResult.CODE_SUCCESS);
                        jsonResult.setMessage("查询成功");
                        jsonResult.setData(resultMap);
                    }
                }
                else
                {
                    Page<IndexData> dataPage = indexDataService.findDefault(pageNumber);
                    resultMap.put("list", dataPage.getContent());
                    resultMap.put("page", new DKQPage(dataPage));
                    jsonResult.setCode(JsonResult.CODE_SUCCESS);
                    jsonResult.setMessage("查询成功");
                    jsonResult.setData(resultMap);
                }
                redisClientTemplate.setex(key, 60*5,JSON.toJSONString(resultMap));
            }
        }catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }

        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

    @RequestMapping(value = "/search/{content}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> search(@PathVariable("content") String content)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            List<SearchResultVO> vos = new ArrayList<SearchResultVO>();
            //查询活动
            List<Activity> acts = this.activityService.findNameLike(content.trim());
            if (null != acts && acts.size() > 0)
                for (Activity activity : acts)
                    vos.add(SearchResultVO.buildActivity(activity));
            //查询社团
            List<Group> groups = this.groupService.findNameLike(content.trim(),10);
            if (null != groups && groups.size() > 0)
                for (Group group : groups)
                    vos.add(SearchResultVO.buildGroup(group));
            //查询话题
            List<SysTopic> topics = this.sysTopicService.findTitleLike(content.trim());
            if (null != topics && topics.size() > 0)
                for (SysTopic topic : topics)
                    vos.add(SearchResultVO.buildTopic(topic));
            //查询社团招募
            List<GroupRecruit> recruits = this.groupRecruitService.findTitleLike(content.trim());
            if (null != recruits && recruits.size() > 0)
                for (GroupRecruit groupRecruit : recruits)
                    vos.add(SearchResultVO.buildGroupRecruit(groupRecruit));
            //查询活动招募
            List<ActivityRecruit> activityRecruits = this.activityRecruitService.findTitleLike(content.trim());
            if (null != activityRecruits && activityRecruits.size() > 0)
                for (ActivityRecruit groupRecruit : activityRecruits)
                    vos.add(SearchResultVO.buildActivityRecruit(groupRecruit));

            if (null != vos && vos.size() > 0)
            {
                sortClass sort = new sortClass();
                Collections.sort(vos, sort);
                Map<String,Object> resultMap = new HashMap<String, Object>();
                resultMap.put("list",vos);
                jsonResult.setData(resultMap);
            }
            else
                jsonResult.setData(new HashMap<String,Object>() );
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

    @RequestMapping(value = "/tag/{tag}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> searchByTag(@PathVariable("tag") String tag)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            List<SearchResultVO> vos = new ArrayList<SearchResultVO>();
            //查询活动
            List<Activity> acts = this.activityService.findTagsLike(tag.trim());
            if (null != acts && acts.size() > 0)
                for (Activity activity : acts)
                    vos.add(SearchResultVO.buildActivity(activity));
            //查询社团
            List<Group> groups = this.groupService.findServiceFieldLike(tag.trim(),10);
            if (null != groups && groups.size() > 0)
                for (Group group : groups)
                    vos.add(SearchResultVO.buildGroup(group));
            //查询话题
            List<SysTopic> topics = this.sysTopicService.findTagsLike(tag.trim());
            if (null != topics && topics.size() > 0)
                for (SysTopic topic : topics)
                    vos.add(SearchResultVO.buildTopic(topic));

            //查询社团招募
            List<GroupRecruit> recruits = this.groupRecruitService.findByJobSkillSerivice(tag.trim());
            if (null != recruits && recruits.size() > 0)
                for (GroupRecruit groupRecruit : recruits)
                    vos.add(SearchResultVO.buildGroupRecruit(groupRecruit));
            //查询活动招募
            List<ActivityRecruit> activityRecruits = this.activityRecruitService.findByJobSkillSerivice(tag.trim());
            if (null != activityRecruits && activityRecruits.size() > 0)
                for (ActivityRecruit groupRecruit : activityRecruits)
                    vos.add(SearchResultVO.buildActivityRecruit(groupRecruit));

            if (null != vos && vos.size() > 0)
            {
                sortClass sort = new sortClass();
                Collections.sort(vos, sort);
                Map<String,Object> resultMap = new HashMap<String, Object>();
                resultMap.put("list", vos);
                jsonResult.setData(resultMap);
            }
            else
                jsonResult.setData(new HashMap<String,Object>() );
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }

        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }
}

class sortClass implements Comparator
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public int compare(Object arg0, Object arg1)
    {
        SearchResultVO v0 = (SearchResultVO) arg0;
        SearchResultVO v1 = (SearchResultVO) arg1;

        try
        {
            Date begin = sdf.parse(v0.getCreateTime());
            Date end = sdf.parse(v1.getCreateTime());
            if (begin.before(end))
            {
                return 1;
            }
            else
            {
                return -1;
            }

        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        return 0;
    }
}

